package com.ruoyi.quartz.util;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.domain.SysJobLog;
import com.ruoyi.quartz.service.ISysJobLogService;

import java.util.Date;

/**
 * 定时任务执行线程
 */
public class RunnableTask implements Runnable {
    private SysJob job;

    public RunnableTask(SysJob job) {
        this.job = job;
    }

    /**
     * 执行任务，并记录日志
     */
    @Override
    public void run() {

        final SysJobLog sysJobLog = new SysJobLog();
        sysJobLog.setJobName(job.getJobName());
        sysJobLog.setJobGroup(job.getJobGroup());
        sysJobLog.setInvokeTarget(job.getInvokeTarget());
        sysJobLog.setStartTime(new Date());

        try {
            JobInvokeUtil.invokeMethod(job);
            sysJobLog.setStatus(Constants.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            sysJobLog.setStatus(Constants.FAIL);
            String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
            sysJobLog.setExceptionInfo(errorMsg);
        }
        sysJobLog.setStopTime(new Date());
        long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime();
        sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时：" + runMs + "毫秒");

        // 写入数据库当中
        SpringUtils.getBean(ISysJobLogService.class).addJobLog(sysJobLog);

    }
}
